package com.zbkj.crmeb.store.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dao.StoreSeasonMapDao;
import com.zbkj.crmeb.store.model.StoreSeasonMap;
import com.zbkj.crmeb.store.request.StoreSeasonMapRequest;
import com.zbkj.crmeb.store.service.StoreSeasonMapService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class StoreSeasonMapServiceImpl extends ServiceImpl<StoreSeasonMapDao, StoreSeasonMap> implements StoreSeasonMapService {
    @Resource
    private StoreSeasonMapDao storeSeasonMapDao;
    @Resource
    private StoreProductDao storeProductDao;


    @Override
    public PageInfo<StoreSeasonMap> pageEntity(StoreSeasonMapRequest request) {
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<StoreSeasonMap> storeSeasons = this.list(Wrappers.<StoreSeasonMap>lambdaQuery()
                .eq(StringUtil.isNotEmpty(request.getName()), StoreSeasonMap::getName, request.getName())
        );

        return CommonPage.copyPageInfo(page, storeSeasons);
    }

    @Override
    public StoreSeasonMap getEntityById(Integer id) {
        return this.getOne(Wrappers.<StoreSeasonMap>lambdaQuery().eq(StoreSeasonMap::getId, id));
    }

    @Override
    public Integer saveEntity(StoreSeasonMap request) {
        request.setCreateTime(new Date());
        request.setUpdateTime(new Date());

        return storeSeasonMapDao.insert(request);
    }

    @Override
    public Integer updateEntity(StoreSeasonMap request) {
        request.setUpdateTime(new Date());

        return storeSeasonMapDao.updateById(request);
    }

    @Override
    public List<StoreSeasonMap> selectEntityList() {
        List<StoreSeasonMap> storeSeasons = this.list(Wrappers.<StoreSeasonMap>lambdaQuery());

        return storeSeasons;
    }

    @Override
    public Integer repair(Integer id) {
        StoreSeasonMap storeSeasonMap = getEntityById(id);
        Assert.notNull(storeSeasonMap, "参数错误");
        return executeRepair(storeSeasonMap);
    }

    public Integer executeRepair(StoreSeasonMap storeSeasonMap) {
        return storeProductDao.repairSeasonCode(storeSeasonMap.getName(), storeSeasonMap.getReplaceName());
    }

    @Override
    public Integer repairAll() {
        List<StoreSeasonMap> storeSeasonMapList = selectEntityList();
        Assert.notEmpty(storeSeasonMapList, "季节映射数据还未创建");
        storeSeasonMapList.parallelStream().forEach(d -> executeRepair(d));
        return 1;
    }
}
